package tr.edu.bilgi.videocs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

import tr.edu.bilgi.videocs.models.Series;
import tr.edu.bilgi.videocs.models.Speaker;
import tr.edu.bilgi.videocs.models.Video;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

/**
 * Lists videos, launches video player when one is clicked
 * 
 */
public class VideoList extends ListActivity {

	private ArrayList<Video> videos;
	ProgressDialog pd;
	private int lastItemIndex = 0;

	private String searchString;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.videolist);
		videos = (ArrayList<Video>) getIntent().getExtras().getSerializable("videos");		
		loadFeed();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		if (videos.get(position).getId() == "-1") {
			videos.remove(position);
			loadFeed();
		} else {
			Intent myIntent = new Intent(this, VidPlayer.class);
			Bundle bundle = new Bundle();
			bundle.putString("URL", videos.get(position).getVideoUrl());
			bundle.putString("title", videos.get(position).getTitle());
			myIntent.putExtras(bundle);
			VideoList.this.startActivity(myIntent);
		}
	}

	@SuppressWarnings("unchecked")
	private void loadFeed() {
		final ListActivity list = this;
		// Toast.makeText(VideoList.this, "Loading..." ,
		// Toast.LENGTH_SHORT).show();
		pd = ProgressDialog.show(this, "Loading...", "Please wait");
		pd.setCancelable(true);
		pd.setOnCancelListener(new OnCancelListener() {

			//@Override
			public void onCancel(DialogInterface arg0) {
				list.finish();
			}

		});

		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message message) {
				list.setListAdapter(((ArrayAdapter) message.obj));
				registerForContextMenu(getListView());
				list.setSelection(lastItemIndex);
				pd.dismiss();
			}
		};

		Thread thread = new Thread() {
			@Override
			public void run() {

				try {
					lastItemIndex = videos.size() - 1;
//					Speaker speaker = new Speaker(1, "Chris");
//					Series series = new Series();
//					series.setId("1");
//					series.setTitle("Comp232");
//
//					String thumb = "http://media.giantbomb.com/uploads/0/30/1803489-screenshot0057_small.jpg";
//					String videoUrl = "http://daily3gp.com/vids/747.3gp";
//
//					Video myVideo = new Video("1", "Lecture1", thumb,
//							videoUrl, speaker, series);
//					videos.add(myVideo);
					
					Message message;
					message = handler.obtainMessage(-1, new VideoListAdapter(
							list, R.layout.videorow, videos));
					handler.sendMessage(message);
				} catch (Throwable t) {
				}
			}
		};
		thread.start();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		final Context context = this;
		menu.clear();

		SubMenu searchVideos = menu.addSubMenu("Search Videos").setIcon(
				android.R.drawable.ic_menu_search);

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());
		String searchStrings = prefs.getString("searchStrings",
				"Trailer, Review, Quick Look, Endurance Run");
		String[] tokens = searchStrings.split(",");
		for (final String search : tokens) {
			if (search == null || "".equals(search.trim())) {
				continue;
			}
			MenuItem mi = searchVideos.add(search.trim());
			mi.setOnMenuItemClickListener(new OnMenuItemClickListener() {
				//@Override
				public boolean onMenuItemClick(MenuItem arg0) {
					Intent myIntent = new Intent(context, VideoList.class);
					Bundle bundle = new Bundle();
					bundle.putString("searchString", search.trim());
					myIntent.putExtras(bundle);
					context.startActivity(myIntent);
					return true;
				}
			});
		}

		MenuItem cm = searchVideos.add("Custom...");
		cm.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			//@Override
			public boolean onMenuItemClick(MenuItem arg0) {
				final EditText et = new EditText(context);

				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setView(et);
				builder.setTitle("Search Videos");
				builder.setMessage("Enter search term");

				et.setOnEditorActionListener(new OnEditorActionListener() {
					//@Override
					public boolean onEditorAction(TextView arg0, int arg1,
							KeyEvent arg2) {
						if (arg1 == EditorInfo.IME_NULL) {
							Intent myIntent = new Intent(context,
									VideoList.class);
							Bundle bundle = new Bundle();
							bundle.putString("searchString", et.getText()
									.toString());
							myIntent.putExtras(bundle);
							context.startActivity(myIntent);
							return true;
						}
						return false;
					}
				});

				AlertDialog dialog = builder.create();
				dialog.setButton("Search", new OnClickListener() {
					//@Override
					public void onClick(DialogInterface arg0, int arg1) {
						Intent myIntent = new Intent(context, VideoList.class);
						Bundle bundle = new Bundle();
						bundle.putString("searchString", et.getText()
								.toString());
						myIntent.putExtras(bundle);
						context.startActivity(myIntent);
					}
				});
				dialog.setButton2("Cancel", new OnClickListener() {
					//@Override
					public void onClick(DialogInterface arg0, int arg1) {
					}
				});
				dialog.show();

				return true;
			}
		});

		return true;
	}

	@Override
	public void onPause() {
		super.onPause();
		if (pd.isShowing()) {
			pd.dismiss();
		}
	}
}